package cn.hbads.version.parser.model;

import cn.hbads.version.annotation.ListVersion;
import cn.hbads.version.provider.ValueTranslator;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;

/**
 * <b> 描述 @ListVersion的列表数据版本解析模型 </b>
 *
 * @author : yvvb
 * @date : 2025/5/5
 */
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ListVersionModel implements VersionModel {
    private String fieldName;
    private Class<?> fieldClass;
    private String orderChangeMessage;
    private String addElementShowName;
    private String removeElementShowName;
    private String separator;
    private ValueTranslator translator;
    private int showOrder;

    public static ListVersionModel buildFrom(Field field, ListVersion listVersion) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Optional<ValueTranslator> translatorOpt = Optional.empty();
        if (!listVersion.translatorClass().equals(ValueTranslator.class)) {
            translatorOpt = Optional.of(listVersion.translatorClass().getDeclaredConstructor().newInstance());
        }
        return ListVersionModel.builder()
                .fieldName(field.getName())
                .fieldClass(field.getType())
                .orderChangeMessage(listVersion.orderChangeMessage())
                .addElementShowName(listVersion.addElementShowName())
                .removeElementShowName(listVersion.removeElementShowName())
                .showOrder(listVersion.showOrder())
                .separator(listVersion.separator())
                .translator(translatorOpt.orElse(null))
                .build();
    }
}
